import axios from 'axios';
import { useAuthStore } from '../stores/auth.js';
// 使用当前域名和端口，如果没有则使用默认值
const protocol = window.location.protocol;
const hostname = window.location.hostname;
const port = window.location.port == '5173' ? '5256' : window.location.port || (protocol === 'https:' ? '443' : '80');

const api = axios.create({
  baseURL: `${protocol}//${hostname}:${port}`, // 后端API地址
  withCredentials: true // 如果需要携带cookie
});

// 请求拦截器 - 添加认证token
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token') || sessionStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器 - 处理认证错误
api.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    if (error.response?.status === 401) {
      const authStore = useAuthStore();
      authStore.forceLogout();
      
      // 如果不在登录页面，则跳转到登录页
      if (window.location.pathname !== '/login') {
        window.location.href = '/login';
      }
    }
    return Promise.reject(error);
  }
);

export default api;
